<template>
  <div class="teacher-dashboard">
    <div class="dashboard-container">
      <!-- 上半部分 -->
      <div class="top-section">
        <!-- 左侧个人信息 -->
        <div class="left-info">
          <el-card class="info-card animated-card">
            <template #header>
              <div class="card-header">
                <span class="header-title">个人信息（{{ teacherInfo.employeeNo }}）</span>
                <el-icon :size="20" color="#409EFF">
                  <User />
                </el-icon>
              </div>
            </template>
            <el-form :model="teacherInfo" label-width="80px" ref="formRef" :rules="formRules">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="teacherInfo.name" />
              </el-form-item>
              <el-form-item label="教龄" prop="teachingYears">
                <el-input-number v-model="teacherInfo.teachingYears">
                  <template #suffix>
                    <span>年</span>
                  </template>
                </el-input-number>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="teacherInfo.email" />
              </el-form-item>
              <el-form-item label="职称" prop="title">
                <el-input v-model="teacherInfo.title" />
              </el-form-item>
              <el-form-item>
                <el-button :loading="submitLoading" type="primary" @click="submitForm" class="submit-btn">
                  保存修改
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>

        <!-- 右侧统计卡片 -->
        <div class="right-stats">
          <div class="stats-grid">
            <el-card v-for="(stat, index) in stats" :key="index" class="stat-card animated-card">
              <div class="stat-content">
                <div class="stat-icon" :style="{ backgroundColor: stat.color }">
                  <component :is="stat.icon" :style="{ color: 'white' }" />
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ stat.value }}</div>
                  <div class="stat-title">{{ stat.title }}</div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>

      <!-- 下半部分 -->
      <div class="bottom-section">
        <el-card class="chart-card animated-card">
          <template #header>
            <div class="card-header">
              <span>班级人数分布</span>
            </div>
          </template>
          <v-chart class="chart" :option="classDistribution" autoresize />
        </el-card>

        <el-card class="chart-card animated-card">
          <template #header>
            <div class="card-header">
              <span>班级试卷分布</span>
            </div>
          </template>
          <v-chart class="chart" :option="examDistribution" autoresize />
        </el-card>
      </div>
    </div>
  </div>
</template>
  
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User, School, Collection, Document, UserFilled } from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import * as echarts from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, BarChart } from 'echarts/charts'
import {
  GridComponent,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GraphicComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { TeacherInfo } from '@/types/teacher'
import { saveInfoApi, getInfoApi, getStatisticsApi,
  getClassDistributionApi,getExamDistributionApi } from '@/api/teacher'


use([
  CanvasRenderer,
  BarChart,
  PieChart,
  GridComponent,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GraphicComponent
])



interface StatItem {
  title: string
  value: number
  icon: any
  color: string
}

// 教师信息
const teacherInfo = reactive<TeacherInfo>({
  name: '',
  employeeNo: '',
  teachingYears: 0,
  email: '0',
  title: ''
})

const stats = ref<StatItem[]>([
  { title: '班级总数', value: 0, icon: School, color: '#409EFF' },
  { title: '题库总数', value: 0, icon: Collection, color: '#e6a23c' },
  { title: '试题总数', value: 0, icon: Document, color: '#67c23a' },
  { title: '试卷总数', value: 0, icon: Document, color: '#f56c6c' },
  { title: '学生总数', value: 0, icon: UserFilled, color: '#909399' }
])

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}


// 班级人数分布饼图配置(动态版本)
const classDistribution = reactive({
  tooltip: {
    trigger: 'item'
  },
  series: [{
    type: 'pie',
    radius: ['40%', '70%'],
    data: [] as { value: number; name: string }[], // 初始化空数组
    itemStyle: {
      borderRadius: 10,
      borderColor: '#fff',
      borderWidth: 2,
      color: (params: any) => {
        // 扩展颜色数组以支持更多班级
        const colors = [
          '#409EFF', '#e6a23c', '#67c23a', '#f56c6c', '#909399',
          '#FF82AB', '#7B68EE', '#00CED1', '#FFD700', '#3CB371',
          '#FFA500', '#6A5ACD', '#20B2AA'
        ];
        return colors[params.dataIndex % colors.length];
      }
    },
    animationType: 'scale',
    animationEasing: 'elasticOut'
  }]
});

const examDistribution = reactive({
  tooltip: {
    trigger: 'item'
  },
  series: [{
    type: 'pie',
    radius: ['40%', '70%'],
    data: [] as { value: number; name: string }[], // 初始化空数组
    itemStyle: {
      borderRadius: 10,
      borderColor: '#fff',
      borderWidth: 2,
      color: (params: any) => {
        // 扩展颜色数组以支持更多班级
        const colors = [
          '#409EFF', '#e6a23c', '#67c23a', '#f56c6c', '#909399',
          '#FF82AB', '#7B68EE', '#00CED1', '#FFD700', '#3CB371',
          '#FFA500', '#6A5ACD', '#20B2AA'
        ];
        return colors[params.dataIndex % colors.length];
      }
    },
    animationType: 'scale',
    animationEasing: 'elasticOut'
  }]
});

// 提交按钮状态
const submitLoading = ref(false)
// 表单提交
const submitForm = async () => {
  try {
    submitLoading.value = true
    const { code, msg } = await saveInfoApi(teacherInfo)
    if (code === 1) {
      ElMessage.success(msg)
    } else {
      ElMessage.error(msg)
    }
  } catch (error) {
    console.log('提交失败', error)
    ElMessage.error('提交失败，请稍后再试')
  } finally {
    submitLoading.value = false
  }

}

/**
 * 获取教师信息
 */
const getTeacherInfo = async () => {
  try {
    const { code, data } = await getInfoApi()
    if (code === 1) {
      teacherInfo.name = data?.name
      teacherInfo.employeeNo = data?.employeeNo
      teacherInfo.teachingYears = data?.teachingYears
      teacherInfo.email = data?.email
      teacherInfo.title = data?.title
    }
  } catch (error) {
    console.log('获取教师信息失败', error)
    ElMessage.error('获取教师信息失败，请稍后再试')
  }
}

/**
* 统计班级总数、题库总数、试题总数、试卷总数、
* 学生总数
*/
const getStatistics = async () => {
  try {
    const { code, data } = await getStatisticsApi()
    if (code === 1) {
      stats.value = stats.value.map(item => {
        switch (item.title) {
          case '班级总数':
            return { ...item, value: data.classCount }; // 13
          case '试卷总数':
            return { ...item, value: data.examCount }; // 5
          case '试题总数':
            return { ...item, value: data.questionCount }; // 568
          case '题库总数':
            return { ...item, value: data.bankCount };
          case '学生总数':
            return { ...item, value: data.studentCount };    
          default:
            return item; // 其他项保持原值（题库总数15，学生总数186）
        }
      });
    }

  } catch (error) {
    console.log('获取统计数据失败', error)
    ElMessage.error('获取统计数据失败，请稍后再试')
  }
}

/**
 * 各班级人数统计
 */
const getClassDistribution = async () => { 
  try {
    const { code, data } = await getClassDistributionApi()
    if(code  === 1){
   // 更新图表数据（通常在数据请求成功后调用）
     classDistribution.series[0].data = processData(data);
    }
  } catch (error) {
    console.log('获取班级人数统计失败', error)
  }
}

// 数据处理逻辑
const processData = (rawData: any[]) => {
  return rawData
    .filter(item => item.totalStudent > 0) // 过滤掉人数为0的班级
    .map(item => ({
      value: item.totalStudent,
      name: item.gradeName
        .replace('2025 ', '') // 移除年份前缀
        .replace(/班$/, '')   // 移除可能存在的"班"后缀
    }));
};

// 数据处理逻辑
const processExamData = (rawData: any[]) => {
  return rawData
    .filter(item => item.total > 0) // 过滤掉人数为0的班级
    .map(item => ({
      value: item.total,
      name: item.gradeName
        .replace('2025 ', '') // 移除年份前缀
        .replace(/班$/, '')   // 移除可能存在的"班"后缀
    }));
};

/**
 * 各班试卷统计
 */
const getExamDistribution = async () => { 
  try {
    const { code, data } = await getExamDistributionApi()
    if(code  === 1){
   // 更新图表数据（通常在数据请求成功后调用）
     examDistribution.series[0].data = processExamData(data);
    }
  } catch (error) {
    console.log('获取班级人数统计失败', error)
  }
}
// 组件挂载时获取教师信息
onMounted(() => {
  getTeacherInfo()
  getStatistics()
  getClassDistribution()
  getExamDistribution()
})
</script>
  
<style lang="scss" scoped>
$primary-color: #409EFF;
$secondary-color: #e6a23c;

.teacher-dashboard {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;

  .dashboard-container {
    max-width: 1400px;
    margin: 0 auto;
  }

  .top-section {
    display: grid;
    grid-template-columns: 1fr 2fr;
    gap: 20px;
    margin-bottom: 20px;

    .left-info {
      .info-card {
        height: 100%;

        :deep(.el-card__header) {
          background-color: rgba($primary-color, 0.1);
        }

        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .header-title {
            color: $primary-color;
            font-weight: bold;
          }
        }

        .submit-btn {
          width: 100%;
          background: linear-gradient(45deg, $primary-color, lighten($primary-color, 10%));
          transition: all 0.3s ease;

          &:hover {
            transform: scale(1.02);
          }
        }
      }
    }

    .right-stats {
      .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 15px;
        height: 100%;

        .stat-card {
          .stat-content {
            display: flex;
            align-items: center;
            padding: 10px;

            .stat-icon {
              width: 40px;
              height: 40px;
              border-radius: 8px;
              display: flex;
              align-items: center;
              justify-content: center;
              margin-right: 15px;
              transition: transform 0.3s ease;

              svg {
                width: 24px;
                height: 24px;
              }
            }

            .stat-info {
              .stat-value {
                font-size: 24px;
                font-weight: bold;
                color: $primary-color;
              }

              .stat-title {
                color: #666;
                font-size: 12px;
              }
            }
          }

          &:hover .stat-icon {
            transform: rotate(15deg) scale(1.1);
          }
        }
      }
    }
  }

  .bottom-section {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;

    .chart-card {
      height: 500px;

      .chart {
        height: 450px;
        transition: all 0.3s ease;

        &:hover {
          transform: scale(0.98);
        }
      }
    }
  }

  .animated-card {
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 10px 20px rgba($primary-color, 0.1);
    }
  }

  @media (max-width: 1200px) {
    .top-section {
      grid-template-columns: 1fr;

      .right-stats {
        margin-top: 20px;
      }
    }

    .bottom-section {
      grid-template-columns: 1fr;

      .chart-card {
        height: 400px;

        .chart {
          height: 350px;
        }
      }
    }
  }
}
</style>